import json
import requests
import uuid
from typing import Dict, Any, Optional, List, Union
import logging
from datetime import datetime

# 修改导入方式，使用绝对导入
try:
    from reqapi.models.query_on_sale_commodity_list import (
        QueryOnSaleCommodityListRequest,
        QueryOnSaleCommodityListResponse,
        CommodityItem,
        Sticker
    )
except ImportError:
    # 如果作为脚本直接运行，使用相对路径导入
    import sys
    import os
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    from reqapi.models.query_on_sale_commodity_list import (
        QueryOnSaleCommodityListRequest,
        QueryOnSaleCommodityListResponse,
        CommodityItem,
        Sticker
    )

logger = logging.getLogger(__name__)


class QueryOnSaleCommodityListAPI:
    """优品898在售商品列表查询API"""
    
    def __init__(self, authorization: str, uk: str, device_id: Optional[str] = None):
        """
        初始化API
        
        Args:
            authorization: 授权令牌
            uk: 用户标识参数
            device_id: 设备ID，如果不提供则自动生成
        """
        self.authorization = authorization
        self.uk = uk
        self.device_id = device_id if device_id else str(uuid.uuid4()).lower()
        self.url = "https://api.youpin898.com/api/homepage/pc/goods/market/queryOnSaleCommodityList"
        
    def get_headers(self) -> Dict[str, str]:
        """
        获取请求头
        
        Returns:
            Dict[str, str]: 请求头字典
        """
        # 生成随机的跟踪ID
        trace_id = f"{uuid.uuid4().hex[:32]}"
        span_id = f"{uuid.uuid4().hex[:16]}"
        
        return {
            "host": "api.youpin898.com",
            "sec-ch-ua": "\"Chromium\";v=\"109\", \"Not_A Brand\";v=\"99\"",
            "appversion": "5.26.0",
            "tracestate": f"rum=v2&browser&hwztx6svg3@74450dd02fdbfcd&53cdba91cab6468c8f41dce25f3cc505&uid_k1ctm7iz36wysgq8",
            "apptype": "1",
            "authorization": self.authorization,
            "b3": f"{trace_id}-{span_id}-1",
            "uk": self.uk,
            "deviceid": self.device_id,
            "sec-ch-ua-platform": "\"Windows\"",
            "traceparent": f"00-{trace_id}-{span_id}-01",
            "sec-ch-ua-mobile": "?0",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36",
            "content-type": "application/json",
            "accept": "application/json, text/plain, */*",
            "secret-v": "h5_v1",
            "platform": "pc",
            "app-version": "5.26.0",
            "origin": "https://www.youpin898.com",
            "sec-fetch-site": "same-site",
            "sec-fetch-mode": "cors",
            "sec-fetch-dest": "empty",
            "referer": "https://www.youpin898.com/",
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "zh-CN,zh;q=0.9"
        }
    
    def query(self, request: Union[QueryOnSaleCommodityListRequest, Dict[str, Any]]) -> QueryOnSaleCommodityListResponse:
        """
        查询在售商品列表
        
        Args:
            request: 请求参数，可以是QueryOnSaleCommodityListRequest对象或字典
            
        Returns:
            QueryOnSaleCommodityListResponse: 响应对象
        
        Raises:
            Exception: 请求失败时抛出异常
        """
        # 如果传入的是字典，转换为请求对象
        if isinstance(request, dict):
            request = QueryOnSaleCommodityListRequest(**request)
            
        # 转换为字典
        request_dict = {
            "gameId": request.gameId,
            "listType": request.listType,
            "templateId": request.templateId,
            "sortTypeKey": request.sortTypeKey,
            "listSortType": request.listSortType,
            "sortType": request.sortType,
            "pageIndex": request.pageIndex,
            "pageSize": request.pageSize
        }
        
        # 添加可选参数
        if request.minAbrade is not None:
            request_dict["minAbrade"] = request.minAbrade
        if request.maxAbrade is not None:
            request_dict["maxAbrade"] = request.maxAbrade
            
        headers = self.get_headers()
        
        print("\n=== 请求信息 ===")
        print(f"请求URL: {self.url}")
        print(f"请求方法: POST")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(request_dict, indent=2, ensure_ascii=False)}")
        
        try:
            response = requests.post(
                self.url, 
                headers=headers, 
                json=request_dict,
                timeout=30  # 添加超时设置
            )
            
            print("\n=== 响应信息 ===")
            print(f"响应码: {response.status_code}")
            print(f"响应头: {json.dumps(dict(response.headers), indent=2, ensure_ascii=False)}")
            resp_json = response.json()
            print(f"响应内容: {json.dumps(resp_json, indent=2, ensure_ascii=False)}")
            
            if resp_json.get('Code', 0) != 0:
                print(f"API返回错误: {resp_json.get('Msg', '未知错误')}")
                return None
            
            commodity_items = []
            if resp_json.get("Data"):
                for item_data in resp_json["Data"]:
                    # 解析贴纸数据
                    stickers = []
                    if item_data.get("stickers"):
                        for sticker_data in item_data["stickers"]:
                            stickers.append(Sticker(
                                id=sticker_data.get("id"),
                                name=sticker_data.get("name"),
                                img=sticker_data.get("img"),
                                wear=sticker_data.get("wear"),
                                slot=sticker_data.get("slot")
                            ))
                    
                    # 创建商品项
                    commodity_item = CommodityItem(
                        id=item_data.get("id"),
                        type=item_data.get("type"),
                        gameId=item_data.get("gameId"),
                        userId=item_data.get("userId"),
                        commodityNo=item_data.get("commodityNo"),
                        commodityName=item_data.get("commodityName"),
                        templateId=item_data.get("templateId"),
                        iconUrl=item_data.get("iconUrl"),
                        iconUrlLarge=item_data.get("iconUrlLarge"),
                        price=item_data.get("price"),
                        publishTime=item_data.get("publishTime"),
                        userNickName=item_data.get("userNickName"),
                        userAvatar=item_data.get("userAvatar"),
                        mine=item_data.get("mine", False),
                        typeName=item_data.get("typeName"),
                        commodityHashName=item_data.get("commodityHashName"),
                        abrade=item_data.get("abrade"),
                        stickers=stickers,
                        actions=item_data.get("actions"),
                        paintSeed=item_data.get("paintSeed"),
                        # 其他可选字段
                        favorite=item_data.get("favorite"),
                        openSublet=item_data.get("openSublet"),
                        newOrder=item_data.get("newOrder"),
                        openNewOrder=item_data.get("openNewOrder"),
                        oldUserId=item_data.get("oldUserId"),
                        steamId=item_data.get("steamId"),
                        steamAssetId=item_data.get("steamAssetId"),
                        steamClassId=item_data.get("steamClassId"),
                        steamInstanceId=item_data.get("steamInstanceId"),
                        steamOfferId=item_data.get("steamOfferId"),
                        selectId=item_data.get("selectId"),
                        floorPrice=item_data.get("floorPrice"),
                        markPrice=item_data.get("markPrice"),
                        markPricePercent=item_data.get("markPricePercent"),
                        number=item_data.get("number"),
                        attach=item_data.get("attach"),
                        remark=item_data.get("remark", ""),
                        reason=item_data.get("reason"),
                        retryNum=item_data.get("retryNum"),
                        attr=item_data.get("attr"),
                        status=item_data.get("status"),
                        frozenTime=item_data.get("frozenTime"),
                        successTime=item_data.get("successTime"),
                        failTime=item_data.get("failTime"),
                        offerTime=item_data.get("offerTime"),
                        onShelfTime=item_data.get("onShelfTime"),
                        offShelfTime=item_data.get("offShelfTime"),
                        updateTime=item_data.get("updateTime"),
                        images=item_data.get("images"),
                        img3d=item_data.get("img3d"),
                        stickerRefreshStatus=item_data.get("stickerRefreshStatus"),
                        haveSticker=item_data.get("haveSticker", 0),
                        haveBuZhang=item_data.get("haveBuZhang", 0),
                        haveNameTag=item_data.get("haveNameTag", 0),
                        canSold=item_data.get("canSold", 1),
                        canLease=item_data.get("canLease"),
                        weaponTypeName=item_data.get("weaponTypeName"),
                        weaponTypeHashName=item_data.get("weaponTypeHashName"),
                        weaponTypeIcon=item_data.get("weaponTypeIcon"),
                        weaponTypeId=item_data.get("weaponTypeId"),
                        leaseUnitPrice=item_data.get("leaseUnitPrice", "0"),
                        longLeaseUnitPrice=item_data.get("longLeaseUnitPrice", "0"),
                        ultraLongLeaseUnitPrice=item_data.get("ultraLongLeaseUnitPrice"),
                        leaseDeposit=item_data.get("leaseDeposit", "0"),
                        openLongLease=item_data.get("openLongLease"),
                        nameTags=item_data.get("nameTags"),
                        isCanSold=item_data.get("isCanSold"),
                        rarityName=item_data.get("rarityName"),
                        rarityColor=item_data.get("rarityColor"),
                        qualityName=item_data.get("qualityName"),
                        qualityColor=item_data.get("qualityColor"),
                        exteriorName=item_data.get("exteriorName"),
                        exteriorColor=item_data.get("exteriorColor"),
                        leaseMaxDays=item_data.get("leaseMaxDays", 8),
                        leaseGiveConfigs=item_data.get("leaseGiveConfigs"),
                        dopplerStatus=item_data.get("dopplerStatus", 0),
                        dopplerName=item_data.get("dopplerName"),
                        dopplerColor=item_data.get("dopplerColor"),
                        fadeStatus=item_data.get("fadeStatus", 0),
                        fadeName=item_data.get("fadeName"),
                        fadeColor=item_data.get("fadeColor"),
                        fadeNumber=item_data.get("fadeNumber"),
                        isHardened=item_data.get("isHardened", 0),
                        hardenedName=item_data.get("hardenedName"),
                        hardenedColor=item_data.get("hardenedColor"),
                        secondDFrontImage=item_data.get("secondDFrontImage"),
                        transPic=item_data.get("transPic"),
                        storeName=item_data.get("storeName", ""),
                        zeroRentLeaseStr=item_data.get("zeroRentLeaseStr"),
                        zeroRentLeasePrice=item_data.get("zeroRentLeasePrice"),
                        zeroRentDepositStr=item_data.get("zeroRentDepositStr"),
                        ultraLongLeaseDays=item_data.get("ultraLongLeaseDays"),
                        commodity_list_type=item_data.get("commodity_list_type", 0),
                        batchNumContent=item_data.get("batchNumContent"),
                        clothContent=item_data.get("clothContent"),
                        groupId=item_data.get("groupId"),
                        mergeList=item_data.get("mergeList", []),
                        tagList=item_data.get("tagList", []),
                        ultraRenterSubsidyPrice=item_data.get("ultraRenterSubsidyPrice"),
                        ultraRenterSubsidyPriceTips=item_data.get("ultraRenterSubsidyPriceTips"),
                        maxSubsidyPrice=item_data.get("maxSubsidyPrice"),
                        cashbackConfigs=item_data.get("cashbackConfigs", []),
                        havePendant=item_data.get("havePendant", 0),
                        pendants=item_data.get("pendants", []),
                        stickerPremiumInfo=item_data.get("stickerPremiumInfo"),
                        autoDeliveryType=item_data.get("autoDeliveryType"),
                        pendantStyle=item_data.get("pendantStyle"),
                        showCS22D=item_data.get("showCS22D", 1)
                    )
                    commodity_items.append(commodity_item)
            
            # 创建响应对象
            response_obj = QueryOnSaleCommodityListResponse(
                Code=resp_json.get("Code"),
                Msg=resp_json.get("Msg"),
                Data=commodity_items,
                TotalCount=resp_json.get("TotalCount", 0)
            )
            
            return response_obj
            
        except requests.exceptions.RequestException as e:
            print(f"请求发生错误: {str(e)}")
            return None
        except Exception as e:
            print(f"处理响应数据失败: {str(e)}")
            return None


def main():
    """主函数，用于测试API"""
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    
    # 替换为你的授权令牌
    authorization = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0OGM1NjM1NmY5YjE0YzkwYmI2ZDhhMjU5ZjNjMjY3ZSIsIm5hbWVpZCI6Ijk1MzQ1OTIiLCJJZCI6Ijk1MzQ1OTIiLCJ1bmlxdWVfbmFtZSI6IuWFqOWkqTgxNTkiLCJOYW1lIjoi5YWo5aSpODE1OSIsInZlcnNpb24iOiJSZEwiLCJuYmYiOjE3NDE0OTc0MzAsImV4cCI6MTc0MjM2MTQzMCwiaXNzIjoieW91cGluODk4LmNvbSIsImRldmljZUlkIjoiODliZTI4YzMtODU1ZS00ODJjLTlkN2UtY2EyMzc3ODVlMGVkIiwiYXVkIjoidXNlciJ9.vsfNt1RyoNwQ0xVidHGehdD5s5Nr_FI5182mUW06tjI"
    uk = "5FDLjNAFdQEqN5frHEmeMoUGuRxmiky5ffdWZzUGugruOCyghLTNDWCoxZl6jE51O"
    
    # 创建API实例，不需要传入device_id，会自动生成
    api = QueryOnSaleCommodityListAPI(authorization, uk)
    
    # 打印生成的device_id
    print(f"自动生成的device_id: {api.device_id}")
    
    # 创建请求参数，只传入必需的参数
    request = QueryOnSaleCommodityListRequest(
        templateId="414",
        minAbrade="0.15",
        maxAbrade="0.18",
        pageIndex=1,
        pageSize=10
    )
    
    try:
        # 发送请求
        response = api.query(request)
        
        print("\n=== 查询在售商品列表结果 ===")
        if response is None:
            print("在售商品查询失败，可能是登录信息失效或接口返回错误。")
        else:
            print(f"请求成功，状态码: {response.Code}, 消息: {response.Msg}")
            print(f"总数: {response.TotalCount}")
            print("商品列表:")
            for i, item in enumerate(response.Data):
                print(f"  {i+1}. {item.commodityName} - 价格: {item.price} - 磨损: {item.abrade}")
            
    except Exception as e:
        print(f"请求失败: {str(e)}")


if __name__ == "__main__":
    main()
